package com.ikingtech.framework.sdk.web.configuration;

import com.ikingtech.framework.sdk.web.properties.WebProperties;
import com.ikingtech.framework.sdk.web.support.agent.FrameworkAgentCaller;
import com.ikingtech.framework.sdk.web.support.agent.FrameworkAgentRunner;
import com.ikingtech.framework.sdk.web.support.agent.LoadBalanceFrameworkAgent;
import com.ikingtech.framework.sdk.web.support.agent.LocalFrameworkAgent;
import com.ikingtech.framework.sdk.web.support.server.FrameworkServerFeedbackCaller;
import com.ikingtech.framework.sdk.web.support.server.FrameworkServerFeedbackRunner;
import com.ikingtech.framework.sdk.web.support.server.LoadBalanceFrameworkServer;
import com.ikingtech.framework.sdk.web.support.server.LocalFrameworkServer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.List;

import static com.ikingtech.framework.sdk.context.constant.CommonConstants.GLOBAL_CONFIG_PREFIX;

/**
 * @author tie yan
 */
@EnableConfigurationProperties({WebProperties.class})
public class WebConfiguration {

    @Bean(initMethod = "init")
    @ConditionalOnProperty(prefix = GLOBAL_CONFIG_PREFIX + ".web", name = "arch", havingValue = "micro_service")
    @ConditionalOnExpression("!'${spring.application.name}'.equals('server')")
    public LoadBalanceFrameworkAgent loadBalanceFrameworkAgent(List<FrameworkAgentCaller> callers) {
        return new LoadBalanceFrameworkAgent(callers);
    }

    @Bean(initMethod = "init")
    @ConditionalOnExpression("null == '${iking.framework.web.arch}' || '${iking.framework.web.arch}'.equals('') || '${iking.framework.web.arch}'.equals('single') || '${spring.application.name}'.equals('server')")
    public LocalFrameworkAgent localFrameworkAgent(List<FrameworkAgentRunner> runners) {
        return new LocalFrameworkAgent(runners);
    }

    @Bean(initMethod = "init")
    @ConditionalOnProperty(prefix = GLOBAL_CONFIG_PREFIX + ".web", name = "arch", havingValue = "micro_service")
    public LoadBalanceFrameworkServer loadBalanceFrameworkServer(List<FrameworkServerFeedbackCaller> callers) {
        return new LoadBalanceFrameworkServer(callers);
    }

    @Bean(initMethod = "init")
    @ConditionalOnProperty(prefix = GLOBAL_CONFIG_PREFIX + ".web", name = "arch", havingValue = "single", matchIfMissing = true)
    public LocalFrameworkServer localFrameworkServer(List<FrameworkServerFeedbackRunner> runners) {
        return new LocalFrameworkServer(runners);
    }
}
